<template>
  <div class="blog">
    <div class="addButton">
      <el-link type="primary" @click.prevent="createBlog">新建博客</el-link>
    </div>
    <div class="blog-table">
      <el-table :data="blogList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="120">
        </el-table-column>
        <el-table-column prop="img" label="封面" width="400">
          <template slot-scope="scope">
            <img :src="scope.row.img" alt="博客封面" id="pic" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="400">
        </el-table-column>
        <el-table-column label="操作" width="310">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="updateBlog(scope.row.id)">编辑</el-button>
            <el-button
              type="text"
              size="small"
              @click="deleteBlog(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import request from "../utils/request";
export default {
  data() {
    return {
      blogList: [],
    };
  },
  methods: {
    //新建博客
    createBlog() {
      this.$router.push("/createblog");
    },
    updateBlog(id){
      this.$router.push(`/createblog?id=${id}`)
    },
    //获取博客
    getBlogList() {
      request.get("blog?page=1&total=100").then((res) => {
        if (res.data.code === 20000) {
          this.blogList = res.data.data;
        } else {
          this.$message.error("获取博客错误");
        }
      });
    },
    //删除博客
    async deleteBlog(id) {
     const {data:res} = await request.delete(`blog/${id}`)
      if (res.code === 20000) {
        this.getBlogList();
        this.$message.success("删除成功");
      } else {
        this.$message.error("删除出错");
      }
    },
  },
  created() {
    this.getBlogList();
  },
};
</script>

<style scoped>
#pic {
  width: 50px;
  height: 50px;
}
.blog-table{
  margin-top: 20px;
}
</style>